package com.example.aslongastoday.ui.reminiscence;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.Toast;

import com.example.aslongastoday.MainActivity;
import com.example.aslongastoday.R;
import com.example.aslongastoday.adapter.ViewMemoryAdapter;
import com.example.aslongastoday.databinding.FragmentReminiscenceEditBinding;
import com.example.aslongastoday.db.dao.MemoryDao;
import com.example.aslongastoday.domain.BackLogGroup;
import com.example.aslongastoday.domain.Memory;
import com.example.aslongastoday.util.TimeUtil;

import java.util.Date;
import java.util.List;

public class ReminiscenceEditFragment extends Fragment implements View.OnTouchListener {

    private DatePicker mDatePicker;
    private Context context;
    private Fragment parentFragment;
    private View root;
    private FragmentReminiscenceEditBinding binding;
    private ImageView backImageView;
    private RadioGroup radioGroup;
    private ImageView selectIcon;
    private ImageView isAnniversaryIcon;
    private Switch switchButton;
    private EditText memoryNameEditText;
    private EditText memoryDiscriptionEditText;
    private Memory memory;
    private Bundle bundle;
    private ImageView checkButton;
    private String type;
    private ViewMemoryAdapter viewMemoryAdapter;
    List<Memory> memoryList;
    private MemoryDao memoryDao;
    private FragmentManager fragmentManager;
    private int year;
    private int month;
    private int day;

    public ReminiscenceEditFragment(ViewMemoryAdapter viewMemoryAdapter,Context context) {
        this.viewMemoryAdapter = viewMemoryAdapter;
        this.context = context;
        this.parentFragment = null;
    }
    public ReminiscenceEditFragment(Fragment parentFragment,Context context) {
        this.context = context;
        this.parentFragment =parentFragment;
    }

    // onTouch事件 将上层的触摸事件拦截
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // 将根布局转化为根视图
        binding = FragmentReminiscenceEditBinding.inflate(inflater, container, false);
        root = binding.getRoot();

        //拦截touch请求, 防止泄露
        root.setOnTouchListener(this);

        // 初始化Dao
        memoryDao = new MemoryDao(getContext());
        // 初始化fragment管理器
        fragmentManager = getActivity().getSupportFragmentManager();

        // 设置好日期选择器
        mDatePicker = root.findViewById(R.id.datePicker);
        // 初始化图片选择器
        radioGroup = root.findViewById(R.id.radioGroup);
        selectIcon = root.findViewById(R.id.iv_selected_icon);
        // 初始化纪念日开关
        isAnniversaryIcon = root.findViewById(R.id.iv_is_anniversary);
        switchButton = root.findViewById(R.id.switch_anniversary);
        // 初始化名称编辑器
        memoryNameEditText = root.findViewById(R.id.editTextMemoryName);
        // 初始化事件描述器
        memoryDiscriptionEditText = root.findViewById(R.id.editText_memory_discription);

        // 判断是编辑原有的Memory还是完全的新建一个新的
        bundle = getArguments();
        if(bundle==null){
            //暂留的预防错误的位置
        }
        else {
            type = bundle.getString("type");
            //界面展示
            switch (type) {
                //编辑回忆项
                case "edit_memory":
                    memory = (Memory) bundle.getSerializable("memory");
                    // 然后要在视图中更新当前传来的参数
                    // 设置日期选择器的时间
                    year = memory.getTime().getYear()+1900;
                    month = memory.getTime().getMonth();
                    day = memory.getTime().getDate();
                    // 设置图片选择器中选中的图片为对应图片
                    selectIcon.setImageResource(memory.getIconID());
                    // 设置纪念日的选中状态和图片状态
                    switchButton.setChecked(memory.isAnniversary());
                    if (memory.isAnniversary()){
                        isAnniversaryIcon.setImageResource(R.drawable.ic_anniversary_heart_24dp);
                    }else {
                        isAnniversaryIcon.setImageResource(R.drawable.ic_set_as_anniversary_24dp);
                    }
                    // 设置回忆项名称
                    memoryNameEditText.setText(memory.getName());
                    // 设置回忆项描述
                    memoryDiscriptionEditText.setText(memory.getMessage());
                    break;
                //新建回忆项
                case "add_memory":
                    // 那就要新建一个回忆项
                    memory = new Memory();
                    // 然后设置默认参数
                    // 默认情况下日期选择器的时间设置为当前时间
                    year = TimeUtil.getNowYear();
                    month = TimeUtil.getNowMonth();
                    day = TimeUtil.getNowDay();
                    // 默认情况下的话就直接设置为当前的时间
                    Date nowDate = new Date();
                    memory.setTime(nowDate);
                    // 如果啥都没选就设置默认的
                    memory.setIconID(R.drawable.reminiscence_1_default_memory);
                    // 默认为非纪念日
                    memory.setAnniversary(false);
                    break;
                default:
                    break;
            }
        }

        // 初始化图片选择器
//        initIconResource();

        // 日期选择器的监听事件
        mDatePicker.init(year,month,day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 需要将日期数据保存到新的回忆项中
                Date newDate = new Date(year-1900,monthOfYear,dayOfMonth);
                memory.setTime(newDate);
            }
        });

        // 图片选择器的监听事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.radioButton1:
                        selectIcon.setImageResource(R.drawable.reminiscence_1_default_memory);
                        memory.setIconID(R.drawable.reminiscence_1_default_memory);
//                        Toast.makeText(context, "1", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.radioButton2:
                        selectIcon.setImageResource(R.drawable.reminiscence_2_important);
                        memory.setIconID(R.drawable.reminiscence_2_important);
//                        Toast.makeText(context, "2", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.radioButton3:
                        selectIcon.setImageResource(R.drawable.reminiscence_3_anniversary);
                        memory.setIconID(R.drawable.reminiscence_3_anniversary);
//                        Toast.makeText(context, "3", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.radioButton4:
                        selectIcon.setImageResource(R.drawable.reminiscence_4_birthdaycake1);
                        memory.setIconID(R.drawable.reminiscence_4_birthdaycake1);
//                        Toast.makeText(context, "4", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.radioButton5:
                        selectIcon.setImageResource(R.drawable.reminiscence_5_birthdaycake2);
                        memory.setIconID(R.drawable.reminiscence_5_birthdaycake2);
//                        Toast.makeText(context, "5", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        // 纪念日设置开关
        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    isAnniversaryIcon.setImageResource(R.drawable.ic_anniversary_heart_24dp);
                }else {
                    isAnniversaryIcon.setImageResource(R.drawable.ic_set_as_anniversary_24dp);
                }
                memory.setAnniversary(isChecked);
            }
        });

        // 实现返回上级功能
        backImageView = root.findViewById(R.id.iv_back);
        backImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出fragment
                fragmentManager.popBackStack();
            }
        });

        // 提交新建请求/编辑请求
        checkButton = root.findViewById(R.id.iv_check);
        checkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (type) {
                    //编辑回忆项
                    case "edit_memory":
                        // 设置好回忆项的名称
                        memory.setName(memoryNameEditText.getText().toString());
                        // 设置好事件描述
                        memory.setMessage(memoryDiscriptionEditText.getText().toString());
                        memoryDao.updateMemory(memory);
//                        Log.i("TEST", "onClick: ."+memory.toString());
                        // 更新视图信息
                        setMemoryDataChange();
                        // 退出fragment
                        fragmentManager.popBackStack();
                        Toast.makeText(context, "编辑回忆项成功~", Toast.LENGTH_SHORT).show();
                        break;
                    //新建回忆项
                    case "add_memory":
                        // 设置好回忆项的名称
                        memory.setName(memoryNameEditText.getText().toString());
                        // 设置好事件描述
                        memory.setMessage(memoryDiscriptionEditText.getText().toString());
                        memoryDao.addMemory(memory);
//                        Log.i("TEST", "onClick: ."+memory.toString());
                        // 更新视图信息
                        setMemoryDataChange();
                        // 退出fragment
                        fragmentManager.popBackStack();
                        Toast.makeText(context, "新建回忆项成功~", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        });


        return root;
    }

    /**
     * 初始化图片选择器中的每一个选项的iCon(准备改成静态)
     */
    public void initIconResource(){
        RadioButton radioButton1 = root.findViewById(R.id.radioButton1);
        radioButton1.setButtonDrawable(R.drawable.reminiscence_1_default_memory);

        RadioButton radioButton2 = root.findViewById(R.id.radioButton2);
        radioButton2.setButtonDrawable(R.drawable.reminiscence_2_important);

        RadioButton radioButton3 = root.findViewById(R.id.radioButton3);
        radioButton3.setButtonDrawable(R.drawable.reminiscence_3_anniversary);

        RadioButton radioButton4 = root.findViewById(R.id.radioButton4);
        radioButton4.setButtonDrawable(R.drawable.reminiscence_4_birthdaycake1);

        RadioButton radioButton5 = root.findViewById(R.id.radioButton5);
        radioButton5.setButtonDrawable(R.drawable.reminiscence_5_birthdaycake2);
    }

    /**
     * 在数据更改后刷新视图
     */
    private void setMemoryDataChange(){
        memoryList = memoryDao.getAllMemories();
        viewMemoryAdapter.setMemoryList(memoryList);
        viewMemoryAdapter.notifyDataSetChanged();
    }

}